package HDFSTest;

import java.util.HashMap;

import org.simgrid.msg.Host;
import org.simgrid.msg.Msg;
import org.simgrid.msg.MsgException;
import org.simgrid.msg.Process;
import org.simgrid.msg.Task;
import org.simgrid.msg.TimeoutException;

public class HDFSNameNode extends Process {
	protected HashMap<String, String[]> fileLocations;

	public HDFSNameNode(Host host, String name, String[] args) {
		super(host, name, args);
	}

	@Override
	public void main(String[] args) throws MsgException {
		Msg.info("HDFSNameNode " + this.getHost().getName() + " started ");
		this.fileLocations = new HashMap<String, String[]>();
		String[] fileNames = args[0].split(",");
		String[] dataNodes = args[1].split(",");

		for (int i = 0; i < fileNames.length; i++) {
			String[] nums = dataNodes[i].split(" ");
			String[] names = new String[nums.length];
			for (int k = 0; k < nums.length; k++)
				names[k] = "dataNode" + k;
			this.fileLocations.put(fileNames[i], names);
		}
		Task received = Task.receive(this.getHost().getName(), 0.5);
		while (received != null) {
			if (received instanceof FileRequest) {

				FileRequest task = (FileRequest) received;

				String fileName = task.getFileName();
				task.setResponse(fileLocations.get(fileName));
				task.send(HDFS.class.getName());

				Msg.info("Handling request for " + task.getFileName());
			}
			try {
				received = Task.receive(this.getHost().getName(), 0.5);
			} catch (TimeoutException e) {
				received = null;
			}
		}

	}

	public void addFileLocations(String file, String[] locations) {
		fileLocations.put(file, locations);
	}

	public boolean hasFile(String file) {
		return fileLocations.containsKey(file);
	}

	public String[] getFileLocation(String file) {
		return fileLocations.get(file);
	}

}
